<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
/**
 * order Controller
 * @author		Jade Xia
 * @copyright	Copyright (c) 2010 - 2011 天夏网络.
 * @link		http://www.tianxianet.com
 */
class Order extends Controller
{
	var $site_title;
	var $floatim = '';
	var $user_id = 0;
	
	function Order()
	{
		parent::Controller();
		$this->load->database();
		$this->load->model('com_model');
		$this->site_title=$this->config->item('sys_site_title');
		$this->load->library('form_validation');
		if($this->config->item('sys_is_open_im') == '1')
		{
			$this->floatim = $this->com_model->floatim();
		}
		if(isset($_COOKIE['user_id']) && $user_id = $_COOKIE['user_id']) $this->user_id = $user_id;
	}
	
	function index()
	{
		$nav = '产品订购';
		$data = array(
			'site_title'		=> $nav.'--'.$this->site_title,
			'nav'		=> ' &gt; '.$nav,
			'total_price' => $this->_get_total_price(),
			'cart_data'		=> $this->_get_cart_records()
		);
		$this->load->view(TPL_FOLDER.'order',$data);
	}
	
	function _get_cart_records()
	{
		$sql = 'SELECT id,price,title,quantity,pic_path,product_id,(quantity * price) AS subtotal FROM '.$this->db->dbprefix.'cart WHERE user_id = ?';
		return $this->common_model->get_records($sql,array($this->user_id));
	}
	
	function _get_radom()
	{
		list($msec, $sec) = explode(' ', microtime()); 
		$sec = (float)$sec;
		srand($sec);
		return date('ymdHis',time()).rand(10,99);
	}
	
	function add_to_cart()
	{
		$this->form_validation->set_rules('rd_id','0','trim|integer');
		$this->form_validation->set_rules('quantity','0','trim|integer');
		if($this->form_validation->run()==FALSE)
		{
			die('0');
		}
		if( ! $this->user_id)
		{
			$user_id = $this->_get_radom();
			setcookie("user_id", $user_id,time()+86400,'/');
			$this->user_id = $user_id;
		}
		$rd_id = $this->input->post('rd_id',true);
		$quantity = $this->input->post('quantity',true);
		
		$cart = $this->common_model->get_record('SELECT id FROM '.$this->db->dbprefix.'cart WHERE product_id = ? AND user_id = ?',array($rd_id,$this->user_id));
		
		if($cart)
		{
			$this->db->simple_query('UPDATE '.$this->db->dbprefix.'cart SET quantity = quantity + '.$quantity.' WHERE product_id = '.$rd_id.' AND user_id = '.$this->user_id);
			
		}
		else
		{
			$product = $this->common_model->get_record('SELECT id,market_price,title,small_pic_path FROM '.$this->db->dbprefix.'product WHERE id = ?',array($rd_id));
			if( ! $product) die('0');
			$data=array(
				'product_id' => $rd_id,
				'price' => $product->market_price,
				'title' => $product->title,
				'quantity' => $quantity,
				'pic_path' => $product->small_pic_path,
				'user_id' => $this->user_id,
				'create_date' => time()
			);
			$this->db->insert('cart',$data);
		}
		die('1');
	}
	
	function update_cart()
	{
		if(! $this->user_id) die('0');
		$this->form_validation->set_rules('rd_id','0','trim|integer');
		$this->form_validation->set_rules('quantity','0','trim|integer');
		if($this->form_validation->run()==FALSE)
		{
			die('0');
		}
		$rd_id = $this->input->post('rd_id',true);
		$quantity = $this->input->post('quantity',true);
		
		if($this->db->simple_query('UPDATE '.$this->db->dbprefix.'cart SET quantity = '.$quantity.' WHERE user_id = '.$this->user_id.' AND id = '.$rd_id))
		{
			$subtotal = $this->common_model->get_record('SELECT (quantity * price) AS subtotal FROM '.$this->db->dbprefix.'cart WHERE id = ?',array($rd_id));
			echo '{"total":"'.$this->_get_total_price().'","subtotal":"'.$subtotal->subtotal.'"}';
		}
		else
		{
			echo '0';
		}
	}
	
	function del_cart()
	{
		if(! $this->user_id) die('0');
		$this->form_validation->set_rules('rd_id','0','trim|integer');
		if($this->form_validation->run()==FALSE)
		{
			die('0');
		}
		$rd_id = $this->input->post('rd_id',true);
		if($this->db->simple_query('DELETE FROM '.$this->db->dbprefix.'cart WHERE user_id = '.$this->user_id.' AND id = '.$rd_id))
		{
			echo '1';
		}
		else
		{
			die('0');
		}
	}
	
	function clear_cart()
	{
		if(! $this->user_id) die('0');
		if($this->db->simple_query('DELETE FROM '.$this->db->dbprefix.'cart WHERE user_id = '.$this->user_id))
		{
			echo '1';
		}
		else
		{
			die('0');
		}
		
	}
	
	function save_order()
	{
		session_start();
		if (strtoupper($this->input->post('validate_code')) !== $_SESSION['validate_code'])
		{
			echo_msg('<li>验证码有误</li>');
		}
		
		if(! $this->user_id)
		{
			$tx_msg='<li>很抱歉，您还没有挑选订购的产品，不能提交订单.</li>';
			echo_msg($tx_msg);
		}
		$cart = $this->common_model->get_record('SELECT id FROM '.$this->db->dbprefix.'cart WHERE user_id = ?',array($this->user_id));
		if( ! $cart)
		{
			$tx_msg='<li>很抱歉，您还没有挑选订购的产品，不能提交订单.</li>';
			echo_msg($tx_msg);
		}
		$this->form_validation->set_rules('true_name','联系人','required');
		$this->form_validation->set_rules('tel','电话','required');
		$this->form_validation->set_rules('email','电子邮箱','valid_email');
		$this->form_validation->set_rules('address','地址','required');
		$tx_msg='';
		if($this->form_validation->run()==FALSE)
		{
			$tx_msg.=validation_errors();
			echo_msg($tx_msg);
		}
		
		$true_name = $this->input->post("true_name",true);
		$tel = $this->input->post("tel",true);
		$detail = $this->input->post("detail",true);
		$email = $this->input->post("email",true);
		$address = $this->input->post("address",true);
		
		$total_price = $this->_get_total_price();
		$trade_num = date("ymd");
		
		$this->db->trans_begin();
		$data=array(
			'user_id'=>$this->user_id,
			'true_name'=>$true_name,
			'tel'=>$tel,
			'email'=>$email,
			'address'=>$address,
			'status'=>0,
			'remark'=>'点击添加备注',
			'total_price'=>$total_price,
			'detail'=>$detail,
			'create_date'=>time()
		);
		$this->db->insert("order",$data);
		
		$this->db->select_max('id');
		$query=$this->db->get('order');
		$row=$query->row();
		$order_id = $row->id;
		
		$this->db->update('order',array('trade_num'=>$trade_num.$order_id),array('id'=>$order_id));
		
		$cart = $this->common_model->get_records('SELECT * FROM '.$this->db->dbprefix.'cart WHERE user_id ='.$this->user_id);
		foreach($cart as $row)
		{
			$data = array(
				'order_id' => $order_id,
				'product_id' => $row->product_id,
				'price' => $row->price,
				'title' => $row->title,
				'quantity' => $row->quantity,
				'pic_path' => $row->pic_path
			);
			$this->db->insert('order_product',$data);
		}
		$this->db->simple_query('DELETE FROM '.$this->db->dbprefix.'cart WHERE user_id ='.$this->user_id);
		
		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
			echo_msg('<li>订单提交失败，请返回重新提交</li>');
		}
		else
		{
			$this->db->trans_commit();
		}
		
		$etpl=get_email_template(2);
		if($etpl->status==1)
		{
			$cart = $this->common_model->get_records('SELECT title,pic_path,quantity,price,product_id,(quantity * price) AS subtotal FROM '.$this->db->dbprefix.'order_product WHERE order_id = '.$order_id);
			$data = array(
				'cart' => $cart,
				'total_price' => $total_price
			);
			$cart_html = $this->load->view(TPL_FOLDER.'email_cart',$data,true);
			$sb=replace_email_template($etpl->title);
			$mg=replace_email_template($etpl->content);
			$mg=str_replace('{tpl_product_info}',$cart_html,$mg);
			$mg=str_replace('{tpl_trade_num}',$trade_num.$order_id,$mg);
			send_email($email,$sb,$mg);
		}
		$etpl=get_email_template(4);
		if($etpl->status==1)
		{
			$this->config->load('customer_email_config',FALSE,TRUE);
			$sb=replace_email_template($etpl->title);
			$mg=replace_email_template($etpl->content);
			$mg=str_replace('{tpl_user_name}',$true_name,$mg);
			$mg=str_replace('{tpl_tel}',$tel,$mg);
			$mg=str_replace('{tpl_email}',$email,$mg);
			$mg=str_replace('{tpl_trade_num}',$trade_num.$order_id,$mg);
			send_email($this->config->item('smtp_re_email'),$sb,$mg);
		}
		$tx_msg='<li>恭喜您，订单提交成功.</li>';
		echo_msg($tx_msg,'','yes');
	}
	
	function _get_total_price()
	{
		$query = $this->common_model->get_record('SELECT SUM(quantity*price) AS total FROM '.$this->db->dbprefix.'cart WHERE user_id = '.$this->user_id);
		if($query)
		{
			return $query->total;
		}
		else
		{
			return 0;
		}
	}
}
?>